/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.psc.controllers;

import com.mycompany.psc.data.Roles;
import com.mycompany.psc.ejb.ResourcesManager;
import com.mycompany.psc.entities.Department;
import com.mycompany.psc.entities.Resource;
import com.mycompany.psc.entities.Users;
import com.mycompany.psc.producers.LoggedIn;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author A7med
 */
@Named
@SessionScoped
public class ResurceBean implements Serializable {
    @Inject
    ProjectsBean p;
    @Inject
    @LoggedIn
    Users current;
    @Inject
    FilesBean fb;
    private String selectedection;
    private String deptartment;
    private Roles selected;
    @EJB
    ResourcesManager rm;
    private List<Resource> filteredResource;
    private StreamedContent downloadfile;
    private Resource selectedResource;
    private TreeNode selectedNode;
    private final Map<Department, TreeNode> trees = new HashMap<>();
    private final Map<String, String> sections = new HashMap<>();
    private String allowedTypes;
    private String fileType;
    @RequestScoped
    private List<UploadedFile> files=new ArrayList<>();
    @Inject
    DepartmentsController dc;

    public StreamedContent getDownloadfile() {
        System.out.println("getting file");
        return downloadfile;
    }

    public void setDownloadfile(StreamedContent downloadfile) {
        this.downloadfile = downloadfile;
    }

    public String getAllowedTypes() {
        return allowedTypes;
    }

    public void setAllowedTypes(String allowedTypes) {
        this.allowedTypes = allowedTypes;
    }

    public StreamedContent getMedia(String contentType) {
        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the image. Get ID value from actual request param.
            String path = p.getSelectedProject().getName();
            String fileName = rm.getPath(selectedResource);
            String section = rm.getSection(selectedResource);
            String type = context.getExternalContext().getRequestParameterMap().get("fileType");
            System.out.println("type=" + fileName);
            downloadfile = fb.getMedia(path, type, section,fileName, contentType);
            return downloadfile;
        }
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public Resource getSelectedResource() {
        return selectedResource;
    }

    public void expandOrCollapse(Department r, boolean option) {
        TreeNode n = trees.get(r);
        if (n != null) {
//        System.out.println("node="+n.getData().toString());
            collapsingORexpanding(n, option);
        }
    }
    
    public void clearList(){
        files.clear();
    }

    private void collapsingORexpanding(TreeNode n, boolean option) {
        // System.out.println("node="+n.getData().toString());
        if (!n.getChildren().isEmpty()) {

            for (TreeNode s : n.getChildren()) {
                collapsingORexpanding(s, option);
            }
        }
        n.setExpanded(option);
        n.setSelected(false);

    }

    public void setSelectedResource(Resource selectedResource) {
        this.selectedResource = selectedResource;
    }

   
    @PostConstruct
    public void init() {

    }

    public List<Resource> getFilteredResource() {
        return filteredResource;
    }

    public void setFilteredResource(List<Resource> filteredResource) {
        this.filteredResource = filteredResource;
    }

    public ArrayList<Roles> getDeparts() {
        ArrayList<Roles> tabs = new ArrayList<>();
        for (Roles r : Roles.values()) {
            if (r.isTab()) {
                tabs.add(r);
            }
        }
        return tabs;
    }

    public void onNodeSelect(NodeSelectEvent event) {
        StringBuilder path = new StringBuilder();
        TreeNode n = event.getTreeNode();
        path.append(getAllParents(n));
        path.append(n.toString());
        String dept = null;
        try {
            dept = path.substring(0, path.indexOf("/"));
        } catch (StringIndexOutOfBoundsException e) {
            dept = path.toString();
        }
        sections.put(dept, path.toString());
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, dept, path.toString());

        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public boolean canCreate(Department r) {
        return true;
// return current.getRoles() == Roles.ADMIN || r == current.getRoles();
    }

    public TreeNode getTree(Department r) {
        if (trees.get(r) != null) {
            return trees.get(r);
        } else {
            TreeNode root = new DefaultTreeNode(r, null);

            if (r != null) {

                addChildren(root, r);

            }
            trees.put(r, root);
            return root;
        }
    }

    public List<Resource> getResources(Department r) {
        return rm.getResources(r.toString(), p.getSelectedProject().getId(), "cost_resource", getSection(r.toString()));
    }

    public String getDeptartment() {
        return deptartment;
    }

    public void resetSection(TabChangeEvent event) {

        sections.clear();
    }

    public void setDeptartment(String deptartment) {
        this.deptartment = deptartment;
    }

   

    public void setUploadedFile(FileUploadEvent event) {
        
        files.add(event.getFile());
        
        System.out.println("files");
    }

    public String saveFileResource() {
        String path=getSection(deptartment);
        String dir = p.getSelectedProject().getName() + "/" +path+ "/" + fileType;
        fb.createDirectory(dir);
        
        System.out.println("path="+path);
        for(UploadedFile u:files){
                fb.handleResUpload(u, dir);
        rm.saveFileResource(u.getFileName(), deptartment, p.getSelectedProject().getId(), current.getName(),path , fileType, u.getFileName());
        }
        files.clear();
        return null;
    }

    public String saveMultiResource(Roles r) {
        System.out.println("multi" + p.getSelectedProject().getId());
        rm.saveMultiResource(10, deptartment, p.getSelectedProject().getId(), current.getName(), r.getSections());
        return null;
    }

    private String getSection(String dept) {
        String result = sections.get(dept);
        if (result == null) {
            return dept;
        } else {
            return result;
        }
    }

   

    public Roles getSelected() {
        return selected;
    }

    public void setSelected(Roles selected) {
        this.selected = selected;
    }

    public SelectItem[] getSectionOptions() {

        SelectItem[] items = new SelectItem[6];

        items[0] = new SelectItem("pdf", "pdf");
        items[1] = new SelectItem("image", "image");
        items[2] = new SelectItem("docs", "docs");
        items[3] = new SelectItem("cad", "cad");
        
        items[4] = new SelectItem("prima", "prima");
        items[5] = new SelectItem("revit", "revit");

        return items;
    }

    public String getSelectedection() {
        return selectedection;
    }

    public void setSelectedection(String selectedection) {
        this.selectedection = selectedection;
    }

    private void addChildren(TreeNode parent, Department r) {

        for (Department child : dc.getDepartsChildren(r.getId())) {
            TreeNode node0 = new DefaultTreeNode(child, parent);

            addChildren(node0, child);

        }

    }

    public TreeNode getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(TreeNode selectedNode) {
        this.selectedNode = selectedNode;
    }

    private String getAllParents(TreeNode treeNode) {
        if (treeNode.getParent() != null) {
            StringBuilder data = new StringBuilder();
            TreeNode parent = treeNode.getParent();
            data.append(getAllParents(parent));
            data.append(parent.toString()).append("/");
            return data.toString();
        } else {
            return "";
        }
    }

    public void deleteResource() {
        rm.deleteResource(selectedResource);
    }
    public void clearResources(Department d){
        System.out.println(d.getDesc());
        rm.clearResource(d, p.getSelectedProject());
    }
}
